题目

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例

img

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

解答

思路

深度优先搜索每一条根到叶子节点的路径,其实就是先序遍历

本题是求所有可行解方案,所以需要保存中间路径,在满足条件时加入最后的答案。在回溯时需要恢复上一层的路径,即把上一层的节点删掉。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
void dfs(TreeNode* root, int t, vector<int>& path){ // 先序遍历dfs
if(root == nullptr){ // 空节点直接下一个
return;
}
path.emplace_back(root->val); // 遍历到当前节点加入路径
t -= root->val; // 更新目标值
if(root->left == nullptr && root->right == nullptr && t == 0){
// 如果到了叶子节点且已满足目标和
res.emplace_back(path); // 把当前路径加入答案
}
//cout<< root->val <<" "<<t<<endl;
dfs(root->left, t, path);
dfs(root->right, t, path);
path.pop_back(); // 路径回溯
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<int> path;
dfs(root, target, path);
return res;
}
};

复杂度

  • 时间复杂度 O(N) :访问树的所有节点。
  • 空间复杂度 O(N) :系统栈空间。